package com.charactereducation.admin.service.impl;

import com.charactereducation.admin.service.AdminUserService;
import com.charactereducation.dao.AdminUserMapper;
import com.charactereducation.module.AdminUser;
import com.charactereducation.tools.MD5Tools;
import com.charactereducation.tools.def.MessageConstant;
import com.charactereducation.tools.myRunTime.MyRunTimeExcption;
import com.charactereducation.webcore.service.ServiceBase;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Andrew  on 2017/1/2.
 */
@Service
public class AdminUserServiceImpl extends ServiceBase implements AdminUserService {
    @Autowired
    AdminUserMapper adminUserMapper;


    @Override
    public AdminUser login(AdminUser adminUser) throws MyRunTimeExcption{
        if(adminUser==null){
            throw new MyRunTimeExcption("没有输入用户名");
        }
        String userName=adminUser.getUserName();
        String passWord=adminUser.getPassWord();

        if(StringUtils.isBlank(userName)){
            throw new MyRunTimeExcption(MessageConstant.NO_USERNAME_ERRO);
        }
        if(StringUtils.isBlank(adminUser.getPassWord())){
            throw new MyRunTimeExcption(MessageConstant.NO_PASSWORD_ERRO);
        }


        adminUser=   adminUserMapper.selectAdminUser(new HashMap<String,String>(){{
            put("userName",userName);
        }});

        if(adminUser==null){
            throw new MyRunTimeExcption(MessageConstant.USERNAME_ERRO);
        }
        if(!adminUser.getPassWord().equals(MD5Tools.MD5(passWord))){
            throw new MyRunTimeExcption(MessageConstant.PASSWORD_ERRO);
        }
        if(adminUser.getStatus()!=AdminUser.STATUS_VALID){
            throw new MyRunTimeExcption(MessageConstant.STATUS_UNVALID);
        }


        return adminUser;
    }

    @Override
    public List<AdminUser> getUserList(Map<String, String> map) {
        return adminUserMapper.selectAdminUserList(map);
    }

    @Override
    public AdminUser getUser(Map<String, String> map) {
        if (!map.containsKey("tid")) {
            throw new MyRunTimeExcption("tid is null");
        }
        return adminUserMapper.selectAdminUser(map);

    }

    @Override
    public AdminUser selectAdminById(Map<String, String> map) {
        return adminUserMapper.selectAdminById(map);
    }

    @Override
    public void modifyUser(AdminUser adminUser) {

        if (adminUser.getTid() == null) {
            adminUser.setCreateTime(new Date());
            adminUser.setPassWord(MD5Tools.MD5("123456"));
            adminUserMapper.insertAdminUser(adminUser);
            return;
        }
        adminUserMapper.updateAdminUserByPrimaryKeySelective(adminUser);
    }
}
